package com.auth.utils;

import com.google.common.collect.Lists;
import com.auth.model.system.SysMenu;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:Tangjiachang
 * @Date 2023/7/16
 * @Description: 树形菜单构建工具
 */
public class MenuHelperUtils {
    public static List<SysMenu> builderTree(List<SysMenu> menus) {
        final List<SysMenu> trees = Lists.newArrayList();
        menus.stream()
                .filter(item -> item.getParentId().intValue() == 0)
                .collect(Collectors.toList())
                .forEach((parentMenu) -> {
                    trees.add(getChildren(parentMenu, menus));
                });
        return trees;
    }

    public static SysMenu getChildren(SysMenu sysMenu, List<SysMenu> menus) {
        sysMenu.setChildren(Lists.newArrayList());
        // 遍历所有的菜单数据,判断id和parentId对应关系
        for (SysMenu menu : menus) {
            if (sysMenu.getId().intValue() == menu.getParentId().intValue()) {
                if (null == sysMenu.getChildren()) {
                    sysMenu.setChildren(Lists.newArrayList());
                }
                sysMenu.getChildren().add(getChildren(menu, menus));
            }
        }
        return sysMenu;
    }
}
